package cur.nature.admin.common;

import cur.nature.framework.mvc.SpringBeanUtil;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

public class MessageUtil {

    public static String getMessage(String code) {
        Locale locale = LocaleContextHolder.getLocale();
        return getMessage(code, null, null, locale);
    }

    public static String getMessage(String code,String defaultMessag) {
        Locale locale = LocaleContextHolder.getLocale();
        return getMessage(code, null, defaultMessag, locale);
    }

    public static String getMessage(String code,String defaultMessag,Locale locale) {
        return getMessage(code, null, defaultMessag, locale);
    }

    public static String getMessage(String code,Object[] args) {
        Locale locale = LocaleContextHolder.getLocale();
        return getMessage(code, args, null, locale);
    }

    public static String getMessage(String code,Object[] args, String defaultMessage) {
        Locale locale = LocaleContextHolder.getLocale();
        return getMessage(code, args, defaultMessage, locale);
    }

    public static String getMessage(String code,Object[] args, String defaultMessage,Locale locale) {
        MessageSource messageSource = SpringBeanUtil.getBean(MessageSource.class);
        return messageSource.getMessage(code, args, defaultMessage, locale);
    }

    // 根据bean所在的路径，读取下面的国际化文件内容
    public static String getBundleMessage(String beanUri, String key, String[] param, Locale locale) {
        ResourceBundle rb = ResourceBundle.getBundle(beanUri, locale);
        String value = rb.getString(key);
        String result = MessageFormat.format(value, param);
        return result;
    }
}

